import 'dart:io';
import 'dart:typed_data';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gallery_saver_plus/gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:dio/dio.dart';
import 'package:wallpaper/components/AlertDialog/loading_dialog.dart';
import 'package:wallpaper/components/images/CustomImageCacheManager.dart';
import 'package:wallpaper/generated/l10n.dart';

class DownImage {
  /// 获取应用总缓存大小 (单位: MB)
  static Future<double> getTotalCacheSize() async {
    double totalSize = 0;
    final tempDir = await getTemporaryDirectory();
    totalSize += await _getFolderSize(tempDir);
    return totalSize;
  }

  /// 清理所有缓存
  static Future<void> clearAllCache() async {
    // 1. 清理内存中的图片缓存
    imageCache.clear();
    imageCache.clearLiveImages();

    // 2. 清理磁盘中的图片缓存
    await DefaultCacheManager().emptyCache();
    await CustomImageCacheManager.instance.cacheManager.emptyCache();
    await clearExtendedImageCache();

    // 3. 清理临时目录
    final tempDir = await getTemporaryDirectory();
    await _deleteFolder(tempDir);

    // 4. 清理其他缓存（按需添加）
    // await SharedPreferences.getInstance().then((prefs) => prefs.clear());
    // await Hive.deleteFromDisk();
  }

  /// 清理 extended_image 特殊缓存
  static Future<void> clearExtendedImageCache() async {
    try {
      final directory = Directory(
          '${(await getTemporaryDirectory()).path}/extended_image_cache');
      if (directory.existsSync()) {
        await directory.delete(recursive: true);
      }
    } catch (e) {
      debugPrint('清理extended_image缓存失败: $e');
    }
  }

  /// 计算文件夹大小
  static Future<double> _getFolderSize(Directory dir) async {
    if (!dir.existsSync()) return 0;

    int totalBytes = 0;
    final files = dir.listSync(recursive: true);

    await Future.forEach(files, (file) async {
      if (file is File) {
        totalBytes += await file.length();
      }
    });

    return totalBytes / (1024 * 1024);
  }

  /// 删除文件夹
  static Future<void> _deleteFolder(Directory dir) async {
    if (dir.existsSync()) {
      // ignore: body_might_complete_normally_catch_error
      await dir.delete(recursive: true).catchError((e) {
        debugPrint('删除文件夹失败');
      });
    }
  }

  /// 传入图片字节数组，返回图片格式（jpg/png/gif/webp）
  static String getImageFormatFromBytes(Uint8List cacheData) {
    // 1. 校验字节数组长度（至少满足最小格式的特征码长度）
    if (cacheData.length < 8) {
      // 最短的 GIF 特征码需要6字节，PNG需要8字节，这里取8字节保底
      return 'unknown';
    }

    // 2. 读取前8字节（覆盖所有常见格式的特征码长度）
    final List<int> header = cacheData.sublist(0, 8); // 取前8字节用于判断

    // 3. 对比特征码判断格式
    // 判断 JPG/JPEG（前3字节：FF D8 FF）
    if (header[0] == 255 && header[1] == 216 && header[2] == 255) {
      return 'jpg';
    }
    // 判断 PNG（前8字节：89 50 4E 47 0D 0A 1A 0A）
    else if (header[0] == 137 &&
        header[1] == 80 &&
        header[2] == 78 &&
        header[3] == 71 &&
        header[4] == 13 &&
        header[5] == 10 &&
        header[6] == 26 &&
        header[7] == 10) {
      return 'png';
    }
    // 判断 GIF（前6字节：GIF87a 或 GIF89a）
    else if (header[0] == 71 &&
        header[1] == 73 &&
        header[2] == 70 &&
        header[3] == 56) {
      if (header[4] == 55 && header[5] == 97) return 'gif'; // GIF87a
      if (header[4] == 57 && header[5] == 97) return 'gif'; // GIF89a
    }
    // 判断 WebP（前4字节 RIFF + 后续包含 WEBP，前8字节需满足：RIFF....WEBP 的前半部分）
    else if (header[0] == 82 &&
        header[1] == 73 &&
        header[2] == 70 &&
        header[3] == 70 &&
        header[4] != 0 &&
        header[5] != 0 &&
        header[6] != 0 &&
        header[7] != 0) {
      // WebP 完整特征：前4字节 RIFF + 4字节长度 + 4字节 WEBP，这里简化判断前4字节+第8字节后是否包含 WEBP
      // 进一步校验：取第8-11字节（RIFF 后第4-7字节）是否为 WEBP（87 69 66 80）
      if (cacheData.length >= 12) {
        // 确保有足够字节判断
        final List<int> webpHeader = cacheData.sublist(8, 12);
        if (webpHeader[0] == 87 &&
            webpHeader[1] == 69 &&
            webpHeader[2] == 66 &&
            webpHeader[3] == 80) {
          return 'webp';
        }
      }
    }

    // 4. 未匹配任何已知格式 默认返回 jpg
    return 'jpg';
  }

  /// 下载网络图片（先读缓存资源，缓存没有再重新获取资源）
  static Future downloadNetworkImage(
      String imagePath, BuildContext context) async {
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      //未授予
      await Permission.storage.request();
    }
    const String prefix = 'App-Save';
    // 获取当前时间戳
    int timestamp = DateTime.now().millisecondsSinceEpoch;
    // 将时间戳转换为可读的日期格式
    String dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp).toString();
    // 拼接名字
    String saveName = '$prefix-$dateTime';

    var loadingClose = LoadingDialog.showLoading(
      context: context,
      message: S.of(context).s14,
      loadingType: 1,
    );

    // 下载逻辑
    late bool? result;
    try {
      // 尝试从缓存获取图片
      final cacheManager = CustomImageCacheManager.instance.cacheManager;
      final file = await cacheManager.getSingleFile(imagePath);
      var cacheData = await file.readAsBytes();
      String suffix = getImageFormatFromBytes(cacheData);
      final tempDir = await getTemporaryDirectory();
      final tempPath = '${tempDir.path}/$saveName.$suffix';
      final tempFile = await File(tempPath).writeAsBytes(cacheData);
      result = await GallerySaver.saveImage(tempFile.path);
    } catch (e) {
      result = false;
      debugPrint('保存图片失败: $e');
    } finally {
      loadingClose();
    }

    if (result == true) {
      BotToast.showText(text: S.of(context).s1);
    } else {
      BotToast.showText(text: 'error，保存失败');
    }
  }

  Future<String?> setWallpaper(String url) async {
    try {
      final dir = await getTemporaryDirectory();
      final filename = url.split('/').last;
      final path = '${dir.path}/$filename';
      final cacheManager = CustomImageCacheManager.instance.cacheManager;
      final file = await cacheManager.getSingleFile(url);
      final cacheData = await file.readAsBytes();
      await File(path).writeAsBytes(cacheData);
      return path;
    } catch (e) {
      debugPrint('下载失败');
      return null;
    }
  }

  // 下载视频到相册
  Future<String?> downVideo(String url, BuildContext context) async {
    try {
      // 请求存储权限
      var status = await Permission.storage.status;
      if (!status.isGranted) {
        // 未授予
        await Permission.storage.request();
      }

      // 获取相册目录
      final directory = await getExternalStorageDirectory();
      final filename = Uri.parse(url).pathSegments.last;
      final filePath = '${directory?.path}/Download/$filename';

      // 确保目录存在
      final downloadDir = Directory('${directory?.path}/Download');
      if (!downloadDir.existsSync()) {
        downloadDir.createSync();
      }

      // 检查文件是否已经存在
      if (File(filePath).existsSync()) {
        return filePath;
      }

      var loadingClose = LoadingDialog.showLoading(
        context: context,
        message: S.of(context).s3,
        loadingType: 1,
      );

      // 使用 Dio 下载文件
      final dio = Dio();
      await dio.download(
        url,
        filePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {}
        },
      );

      // 刷新媒体库（可选）
      // 如果需要让相册应用识别新文件，可以调用媒体扫描
      await GallerySaver.saveVideo(filePath);
      loadingClose();
      return filePath;
    } catch (e) {
      return null;
    }
  }
}
